package tech.daoxuan.security.browser;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import tech.daoxuan.security.browser.support.SimpleRespose;
import tech.daoxuan.security.core.properties.SecurityProperties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class BroserSecurityController {

            Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 从缓存中拿取要访问的路径
     */
    private RequestCache requestCache= new HttpSessionRequestCache();

    //spring 的一个引发跳转的工具
    private RedirectStrategy redirectStrategy=new DefaultRedirectStrategy();


    /**
     * 注入封装的配置，如果配置 则生效
     */
    @Autowired
    private SecurityProperties securityProperties;


    @RequestMapping("/authentication/require")//安全配置地方额loginPage换成这个路径
    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
    public SimpleRespose requireAuthentication(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //原先的请求
        SavedRequest request1 = requestCache.getRequest(request, response);

        if (request1 !=null){
            String redirectUrl = request1.getRedirectUrl();
            logger.info("引发跳转的请求时"+redirectUrl);
            if (StringUtils.endsWithIgnoreCase(redirectUrl,".html")){
                logger.info("该访问时 Web 链接");
                //跳转的工具
                redirectStrategy.sendRedirect(request,response,securityProperties.getBrowser().getLoginPage());
            }else {
                logger.info("该访问时移动访问 ");
            }
        }
        return new SimpleRespose("访问的服务需要身份认证");

    }

}
